package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author yhl
 * @create 2021-09-25 16:39
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 获取分类数据
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    // 获取首页
    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model){

        long l1 = System.currentTimeMillis();
        // 1.查询所用的1级分类
        List<CategoryEntity> categoryEntityList
                = categoryService.getLevel1Categorys();

        long l2 = System.currentTimeMillis();
        System.out.println("消耗的时间：" + (l2 -l1));

        model.addAttribute("categorys", categoryEntityList);
        // 视图解析器进行拼串
        return "index";
    }

    /**
     * 分布式锁的测试
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        // 1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        // 2.加锁
        lock.lock(); // 阻塞式等待，默认加的锁时间是30s
        // 1)、锁的自动续期，运行期间自动给锁续上新的30s，不用担心业务时间长，锁自动过期被删除
        // 2)、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除

        lock.lock(30, TimeUnit.SECONDS); // 指定上锁时间，取消看门狗的时间
        try {
            System.out.println("加锁成功，执行任务。。。" + Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){
        }finally {
            // 3.解锁
            System.out.println("释放锁。。。");
            lock.unlock();
        }

        return "hello";
    }

    // 保证一定能读到最新的数据
    // 修改期间写锁是一个排他锁(互斥锁)，读锁是一个共享锁
    // 写锁没释放读就必须等待
    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        // 1、改变数据加写锁
        RLock wLock = lock.writeLock();
        wLock.lock();
        System.out.println("写锁加锁成功。。。" + Thread.currentThread().getId());

        String s = null;
        try {
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s); // 向缓存中写数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放写锁
            wLock.unlock();
            System.out.println("写锁释放" + Thread.currentThread().getId());
        }
        return s;
    }
    @ResponseBody
    @GetMapping("/read")
    public String readValue(){
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        // 读数据加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        System.out.println("读锁加锁成功。。。" + Thread.currentThread().getId());
        String s = null;
        try {
            Thread.sleep(30000);
             s = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放读锁
            rLock.unlock();
            System.out.println("读锁释放" + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 放假，锁门
     * 5 个班全部走完，我们可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor(){
        // 加闭锁
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        // 设置闭锁等待数
        door.trySetCount(5);
        try {
            door.await();// 等待闭锁都完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "放假了...";
    }
    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();// 计数减 1

        return id+"班的人都走了...";
    }


    /**
     * 车库停车
     * 3 车位
     * 信号量也可以用作分布式限流
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        // 阻塞式，一直等待
        park.acquire();// 获取一个信号，获取一个值，占一个车位
        return "ok";
    }
    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();// 释放一个车位

        return "ok";
    }
}
